package com.xiaotu.spider.maoyan.pageprocessor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.MovieRecordModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.spider.AUrlPageProcessor;

import us.codecraft.webmagic.Page;

/**
 * @类名 MaoYanDayBoxOfficePageProcessor
 * @日期 2019年2月15日
 * @作者 王艳龙
 * @功能 猫眼票房爬取
 */
@Component("MaoYanDayPageProcessor")
public class MaoYanDayPageProcessor extends AUrlPageProcessor
{

    public static final String LIST_URL = "http://piaofang.maoyan.com/dashboard-ajax/movie?showDate=%s&orderType=0";//列表地址

    private String beginDate = DateUtils.getDateString(getYesterday(), DateUtils
            .FILE_NOMENCLATURE_FORMAT);

    @Override
    public void initRunParams(Map<String, Object> map)
    {
        if (map.get("beginDate") != null)
            this.beginDate = map.get("beginDate").toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void process(Page page)
    {
        
        this.listProcess(page);
        
    }

    private void listProcess(Page page)
    {
        String json = page.getRawText();
        if (StringUtils.isEmpty(json))
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        Map<String, Object> map = GsonUtils.fromJson(json, Map.class);
        if (map == null || map.isEmpty() || map.get("movieList") == null)
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        Map<String, Object> dataMap = ((Map<String, Object>) map.get("movieList"));
        List<Map<String, Object>> movList = (List<Map<String, Object>>) dataMap.get("list");

        if (movList == null || movList.isEmpty())
            throw new SpiderException(SpiderExceptionCode.DataInvalideException);
        List<MovieRecordModel> list = new ArrayList<>();
        movList.forEach(movMap ->
        {

            Map<String, Object> movieInfo = (Map<String, Object>) movMap.get("movieInfo");
            String dataId = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, StringUtil
                    .nullToString(movieInfo.get("movieId")));
            Map<String, Object> boxSplitUnit = (Map<String, Object>) movMap.get("boxSplitUnit");
            String box = StringUtil.nullToString(boxSplitUnit.get("num"))+ StringUtil.nullToString(boxSplitUnit.get("unit"));

            String releaseDateCount = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, StringUtil
                    .nullToString(movieInfo.get("releaseInfo")));
            String queryDate = DateUtils.getBeforeDayDynamic(new Date(),1);
            list.add(new MovieRecordModel(Constants.TargetType.OTHER_TYPE_ID,
                    StringUtil.nullToString(movieInfo.get("movieName")),
                    StringUtil.nullToString(box), // 当日票房
                    StringUtil.nullToString(movMap.get("sumBoxDesc")), // 总票房
                    StringUtil.nullToString(movMap.get("showCountRate")), // 排片比
                    StringUtil.nullToString(movMap.get("boxRate")), // 票房百分比
                    StringUtil.nullToString(movMap.get("showCount")), // 当日场次
                    StringUtil.nullToString(releaseDateCount), // 上映天数
                    StringUtil.nullToString(queryDate), // 上映日期
                    StringUtil.nullToString(movMap.get("avgSeatView")), // 上座率
                    StringUtil.nullToString(movMap.get("avgShowView")), // 场均人次
                    null, // 座位数
                    StringUtil.nullToString(null), // 排座占比
                    Constants.SiteName.MAOYAN, //网站名称
                    dataId)//网站电影id
            );

        });

        page.putField(MovieRecordModel.class.getName(), list);
    }

    @Override
    protected String[] getStartRequestUrls()
    {
        return new String[]{String.format(LIST_URL, this.beginDate)};
    }

    @Override
    protected String getSpiderType()
    {
        return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
    }

    @Override
    public String getPageDataType(Page page)
    {
        return Constants.PageDataType.SEARCH_LIST;
    }
    
    /**
     * 获取前一天的日期
     * @return
     */
    public Date getYesterday(){
    	Calendar ca = Calendar.getInstance();
    	ca.setTime(new Date());
    	ca.add(Calendar.DATE, -1); 
    	Date lastDate = ca.getTime(); 
    	return lastDate;
    }

}
